<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="800px" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="150px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="排班日期" prop="scheduleDate">
              <el-date-picker clearable v-model="formData.scheduleDate" type="date"  value-format="yyyy-MM-dd"
                              placeholder="选择排班日期" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车间" prop="deptId">
              <treeselect v-model="formData.deptId" :options="deptList" :normalizer="normalizer"
                          placeholder="选择车间" style="width: 100%" @select="handleDeptSelect" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="班组" prop="teamId">
              <el-select v-model="formData.teamId" placeholder="请选择班组" clearable style="width: 100%" @change="handleTeamChange">
                <el-option v-for="team in teamList" :key="team.id" :label="team.teamName" :value="team.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="班次" prop="shiftId">
              <el-select v-model="formData.shiftId" placeholder="请选择班次" clearable style="width: 100%" @change="handleShiftChange">
                <el-option v-for="shift in shiftList" :key="shift.id" :label="shift.shiftName" :value="shift.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="生产班次开始时间" prop="shiftStartTime">
              <el-time-picker clearable v-model="formData.shiftStartTime" format="HH:mm:ss" value-format="HH:mm:ss"
                              placeholder="选择生产班次开始时间" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生产班次结束时间" prop="shiftEndTime">
              <el-time-picker clearable v-model="formData.shiftEndTime" format="HH:mm:ss" value-format="HH:mm:ss"
                              placeholder="选择生产班次结束时间" style="width: 100%"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="总时长(min)" prop="shiftTotalTime">
              <el-input v-model="formData.shiftTotalTime" placeholder="自动计算" readonly style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划停机时间(min)" prop="planStopTime">
              <el-input v-model.number="formData.planStopTime" placeholder="请输入计划停机时间" style="width: 100%"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="计划休息时间(min)" prop="planRestTime">
              <el-input v-model.number="formData.planRestTime" placeholder="请输入计划休息时间" style="width: 100%"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remarks">
              <el-input v-model="formData.remarks" placeholder="请输入备注" type="textarea" :rows="3" style="width: 100%"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as ScheduleApi from '@/api/system/schedule';
import {getDictDatas, getDictDataLabel, DICT_TYPE} from '@/utils/dict'
import { listDept } from "@/api/system/dept";
import * as ShiftApi from '@/api/system/shift';
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "ScheduleForm",
  components: {
    Treeselect
  },
  data() {
    return {
      // 弹出层标题
      dialogTitle: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 部门列表
      deptList: [],
      // 班次列表
      shiftList: [],
      // 班组列表
      teamList: [],
      // 表单参数
      formData: {
        id: undefined,
        scheduleDate: undefined,
        deptId: undefined,
        deptName: undefined,
        teamId: undefined,
        teamName: undefined,
        shiftId: undefined,
        shiftName: undefined,
        shiftStartTime: undefined,
        shiftEndTime: undefined,
        shiftTotalTime: undefined,
        remarks: undefined,
        planStopTime: undefined,
        planRestTime: undefined,
      },
      // 表单校验
      formRules: {
        scheduleDate: [{ required: true, message: '排班日期不能为空', trigger: 'blur' }],
        deptId: [{ required: true, message: '车间不能为空', trigger: 'change' }],
        teamId: [{ required: true, message: '班组不能为空', trigger: 'change' }],
        shiftId: [{ required: true, message: '班次不能为空', trigger: 'change' }],
        shiftStartTime: [{ required: true, message: '生产班次开始时间不能为空', trigger: 'blur' }],
        shiftEndTime: [{ required: true, message: '生产班次结束时间不能为空', trigger: 'blur' }]
      },
    };
  },
  created() {
    this.getDeptList();
    this.getShiftList();
    this.getTeamList();
  },
  watch: {
    // 监听开始时间和结束时间变化，计算总时长
    'formData.shiftStartTime': function() {
      this.calculateTotalTime();
    },
    'formData.shiftEndTime': function() {
      this.calculateTotalTime();
    }
  },
  methods: {
    /** 打开弹窗 */
    async open(id) {
      this.dialogVisible = true;
      this.reset();
      // 修改时，设置数据
      if (id) {
        this.formLoading = true;
        try {
          const res = await ScheduleApi.getSchedule(id);
          this.formData = res.data;
          this.dialogTitle = "编辑排班";
        } finally {
          this.formLoading = false;
        }
      } else {
        this.dialogTitle = "新增排班";
      }
    },

    /** 获取部门列表 */
    getDeptList() {
      listDept().then(response => {
        this.deptList = this.handleTree(response.data, "id")[0]?.children || [];
      });
    },

    /** 处理树形数据 */
    handleTree(data, id, parentId, children, rootId) {
      id = id || 'id';
      parentId = parentId || 'parentId';
      children = children || 'children';
      rootId = rootId || Math.min.apply(Math, data.map(item => { return item[parentId] || 0 })) || 0;
      // 对源数据深度克隆
      const cloneData = JSON.parse(JSON.stringify(data));
      // 循环所有项
      const treeData = cloneData.filter(father => {
        const branchArr = cloneData.filter(child => {
          // 返回每一项的子级数组
          return father[id] === child[parentId];
        });
        branchArr.length > 0 ? father[children] = branchArr : delete father[children];
        // 返回第一层
        return father[parentId] === rootId;
      });
      return treeData.length > 0 ? treeData : cloneData;
    },

    /** 部门节点格式化 */
    normalizer(node) {
      const normalizedNode = {
        id: node.id,
        label: node.name,
        children: node.children,
      };
      if (node.deptType == 3) {
        normalizedNode.isDisabled = true;
      }
      return normalizedNode;
    },

    /** 部门选择处理 */
    handleDeptSelect(node) {
      this.formData.deptName = node?.name || '';
    },

    /** 获取班次列表 */
    getShiftList() {
      // 使用分页参数获取默认100条班次数据
      ShiftApi.getShiftPage({ pageSize: 100 }).then(response => {
        this.shiftList = response.data.list || [];
      });
    },

    /** 获取班组列表 */
    getTeamList() {
      // 假设使用班次API获取班组数据，默认100条
      ShiftApi.getShiftPage({ pageSize: 100 }).then(response => {
        this.teamList = response.data.list || [];
      });
    },

    /** 班次选择处理 */
    handleShiftChange(shiftId) {
      const shift = this.shiftList.find(item => item.id === shiftId);
      if (shift) {
        this.formData.shiftName = shift.shiftName;
        // 如果有班次时间信息，自动填充
        if (shift.shiftStartTime) {
          this.formData.shiftStartTime = shift.shiftStartTime;
        }
        if (shift.shiftEndTime) {
          this.formData.shiftEndTime = shift.shiftEndTime;
        }
        if (shift.shiftTotalTime) {
          this.formData.shiftTotalTime = shift.shiftTotalTime;
        }
        if (shift.planStopTime) {
          this.formData.planStopTime = shift.planStopTime;
        }
        if (shift.planRestTime) {
          this.formData.planRestTime = shift.planRestTime;
        }
      }
    },

    /** 班组选择处理 */
    handleTeamChange(teamId) {
      const team = this.teamList.find(item => item.id === teamId);
      if (team) {
        this.formData.teamName = team.teamName;
      }
    },

    /** 计算总时长 */
    calculateTotalTime() {
      if (this.formData.shiftStartTime && this.formData.shiftEndTime) {
        const [startHours, startMinutes, startSeconds] = this.formData.shiftStartTime.split(':').map(Number);
        const [endHours, endMinutes, endSeconds] = this.formData.shiftEndTime.split(':').map(Number);

        // 计算开始时间的总分钟数
        const startTotalMinutes = startHours * 60 + startMinutes + startSeconds / 60;
        // 计算结束时间的总分钟数
        const endTotalMinutes = endHours * 60 + endMinutes + endSeconds / 60;

        // 如果结束时间小于开始时间，认为是跨天
        let totalMinutes;
        if (endTotalMinutes < startTotalMinutes) {
          totalMinutes = endTotalMinutes + 24 * 60 - startTotalMinutes;
        } else {
          totalMinutes = endTotalMinutes - startTotalMinutes;
        }

        this.formData.shiftTotalTime = Math.round(totalMinutes);
      }
    },

    /** 提交按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs["formRef"].validate();
      this.formLoading = true;
      try {
        const data = this.formData;
        // 修改的提交
        if (data.id) {
          await ScheduleApi.updateSchedule(data);
          this.$modal.msgSuccess("修改成功");
          this.dialogVisible = false;
          this.$emit('success');
          return;
        }
        // 添加的提交
        await ScheduleApi.createSchedule(data);
        this.$modal.msgSuccess("新增成功");
        this.dialogVisible = false;
        this.$emit('success');
      } finally {
        this.formLoading = false;
      }
    },

    /** 表单重置 */
    reset() {
      this.formData = {
        id: undefined,
        scheduleDate: undefined,
        deptId: undefined,
        deptName: undefined,
        teamId: undefined,
        teamName: undefined,
        shiftId: undefined,
        shiftName: undefined,
        shiftStartTime: undefined,
        shiftEndTime: undefined,
        shiftTotalTime: undefined,
        remarks: undefined,
        planStopTime: undefined,
        planRestTime: undefined,
      };
      this.resetForm("formRef");
    }
  }
};
</script>
